package org.beetl.fn;

import org.beetl.core.Format;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2015/12/8.
 */
public class ItBlogDateFormat implements Format {

    private static final String DEFAULT_KEY = "default";

    private ThreadLocal<Map<String, SimpleDateFormat>> threadlocal = new ThreadLocal<Map<String, SimpleDateFormat>>();

    public Object format(Object data, String pattern) {
        String result = null;
        if (data == null){
            result =  null;
        } else  {
            if (Date.class.isAssignableFrom(data.getClass())) {
                SimpleDateFormat sdf = null;
                if (pattern == null) {
                    result = createAt((Date) data);
                } else if ("at".equalsIgnoreCase(pattern)){
                    result = createAt((Date)data);
                } else {
                    sdf = getDateFormat(pattern);
                    result = sdf.format((Date) data);
                }
            } else if (data.getClass() == Long.class) {
                Date date = new Date((Long) data);
                SimpleDateFormat sdf = null;
                if (pattern == null) {
                    sdf = getDateFormat(DEFAULT_KEY);
                    result = sdf.format(date);
                } else if ("at".equalsIgnoreCase(pattern)){
                    result = createAt(date);
                } else {
                    sdf = getDateFormat(pattern);
                    result = sdf.format(date);
                }
            } else {
                throw new RuntimeException("参数错误，输入为日期或者Long:" + data.getClass());
            }
        }
        return  result;
    }


    public static String createAt(Date date) {
        if (date == null)
            return "未知";
        long now = System.currentTimeMillis() / 1000;
        long t = date.getTime() / 1000;
        long diff = now - t;
        if (diff < 5) {
            return "刚刚";
        }
        if (diff < 60) {
            return diff+"秒前";
        }
        if (diff < 60*60) {
            return (diff/60)+"分钟前";
        }
        if (diff < 24*60*60) {
            return (diff/60/60)+"小时";
        }
        return (diff/24/60/60)+"天前";
    }

    private SimpleDateFormat getDateFormat(String pattern) {
        Map<String, SimpleDateFormat> map = null;
        if ((map = threadlocal.get()) == null) {
            /**
             * 初始化2个空间
             */
            map = new HashMap<String, SimpleDateFormat>(4, 0.65f);
            threadlocal.set(map);
        }
        SimpleDateFormat format = map.get(pattern);
        if (format == null) {
            if (DEFAULT_KEY.equals(pattern)) {
                format = new SimpleDateFormat();
            } else {
                format = new SimpleDateFormat(pattern);
            }
            map.put(pattern, format);
        }
        return format;
    }
}
